<?php

/**
 * @package site
 */

class BonusSummaryReport extends SS_Report implements PermissionProvider {
	protected $total = array();
	
	public function title() {
		return _t('BonusSummaryReport.TITLE', 'Bonus Summary Report');
	}
	
	/**
	 * @param Member $member
	 * @return boolean
	 */
	public function canView($member = null) {
		if(!$member && $member !== FALSE) {
			$member = Member::currentUser();
		}
		
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if($extended !== null) return $extended;

        return Permission::check('VIEW_BonusSummaryReport');
	}
	
	public function extendedCan($methodName, $member) {
		$results = $this->extend($methodName, $member);
		if($results && is_array($results)) {
			// Remove NULLs
			$results = array_filter($results, function($v) {return !is_null($v);});
			// If there are any non-NULL responses, then return the lowest one of them.
			// If any explicitly deny the permission, then we don't get access 
			if($results) return min($results);
		}
		return null;
	}
	
	public function getCMSFields() {
		$fields = new FieldList();

		if($title = $this->title()) {
			$fields->push(new LiteralField('ReportTitle', "<h3>{$title}</h3>"));
		}
		
		if($description = $this->description()) {
			$fields->push(new LiteralField('ReportDescription', "<p>" . $description . "</p>"));
		}
			
		// Add search fields is available
		if($this->hasMethod('parameterFields') && $parameterFields = $this->parameterFields()) {
			foreach($parameterFields as $field) {
				// Namespace fields for easier handling in form submissions
				$field->setName(sprintf('filters[%s]', $field->getName()));
				$field->addExtraClass('no-change-track'); // ignore in changetracker
				$fields->push($field);
			}

			// Add a search button
			$fields->push(new FormAction('updatereport', _t('GridField.Filter')));
		}
		
		$fields->push($this->getReportField());
		
		$fields->insertBefore(NumericField_Readonly::create('TotalSalesAmount', _t('BonusSummaryReport.TOTAL_SALES_AMOUNT', 'Total Sales Amount'), DBField::create_field('Currency', $this->total['CPSA'])->Nice()), 'Report');
		$fields->insertBefore(NumericField_Readonly::create('TotalSalesBV', _t('BonusSummaryReport.TOTAL_SALES_BV', 'Total Sales BV'), DBField::create_field('Int', $this->total['CPBV'])->Formatted()), 'Report');
		$fields->insertBefore(NumericField_Readonly::create('TotalIssuedBV', _t('BonusSummaryReport.TOTAL_ISSUED_BV', 'Total Issued BV'), DBField::create_field('Int', $this->total['CADJLPGBV'] + $this->total['CADJRPGBV'])->Formatted()), 'Report');
		$unilevel_percentage = $this->total['CPBV'] ? $this->total['BS1'] / $this->total['CPBV'] : 0;
		$invest_percentage = $this->total['CPBV'] ? $this->total['BS2'] / $this->total['CPBV'] : 0;
		$matching_percentage = $this->total['CPBV'] ? $this->total['BS3'] / $this->total['CPBV'] : 0;
		$pairing_percentage = $this->total['CPBV'] ? $this->total['BS4'] / $this->total['CPBV'] : 0;
		$payout_field = FieldGroup::create(
			ReadonlyField::create('TotalUnilevelBonus', _t('BonusSummaryReport.TOTAL_UNILEVEL_BONUS', 'Total Unilevel Bonus'), sprintf('%s (%s)', DBField::create_field('Currency', $this->total['BS1'])->Nice(), DBField::create_field('Percentage', $unilevel_percentage)->Nice())),
			ReadonlyField::create('TotalInvestBonus', _t('BonusSummaryReport.TOTAL_INVEST_PROGRAM_BONUS', 'Total Invest Program Bonus'), sprintf('%s (%s)', DBField::create_field('Currency', $this->total['BS2'])->Nice(), DBField::create_field('Percentage', $invest_percentage)->Nice())),
			ReadonlyField::create('TotalMatchingBonus', _t('BonusSummaryReport.TOTAL_MATCHING_BONUS', 'Total Matching Bonus'), sprintf('%s (%s)', DBField::create_field('Currency', $this->total['BS3'])->Nice(), DBField::create_field('Percentage', $matching_percentage)->Nice())),
			ReadonlyField::create('TotalPairingBonus', _t('BonusSummaryReport.TOTAL_PAIRING_BONUS', 'Total Pairing Bonus'), sprintf('%s (%s)', DBField::create_field('Currency', $this->total['BS4'])->Nice(), DBField::create_field('Percentage', $pairing_percentage)->Nice()))
		);
		$fields->insertBefore($payout_field, 'Report');
		$payout_percentage = $this->total['CPBV'] ? ($this->total['BS1'] + $this->total['BS3'] + $this->total['BS4']) / $this->total['CPBV'] : 0;
		$fields->insertBefore(ReadonlyField::create('TotalBonusPayout', _t('BonusSummaryReport.TOTAL_BONUS_PAYOUT', 'Total Bonus Payout'), sprintf('%s (%s)', DBField::create_field('Currency', $this->total['BS1'] + $this->total['BS3'] + $this->total['BS4'])->Nice(), DBField::create_field('Percentage', $payout_percentage)->Nice())), 'Report');

		$this->extend('updateCMSFields', $fields);
		
		return $fields;
	}
	
	public function sourceRecords($params, $sort, $limit) {
		if($sort) {
			$parts = explode(' ', $sort);
			$field = $parts[0];
			$direction = $parts[1];
			
			if($field == 'Name') {
			    $sort = 'FirstName ' . $direction;
			}
		}

		$where = array('Member.IsDistributor = 1');
		if(isset($params['Submit']) && $params['Submit']){
			if(isset($params['StartDate']) && $params['StartDate']){
	        	$where[] = sprintf("DATE(BonusSummary.Date) >= '%s'", DBField::create_field('Date', $params['StartDate'])->URLDate());
	        }
		}
		else{
        	$where[] = sprintf("DATE(BonusSummary.Date) >= '%s'", date('Y-m-01'));
        }
		
		if(isset($params['Submit']) && $params['Submit']){
			if(isset($params['EndDate']) && $params['EndDate']){
	        	$where[] = sprintf("DATE(BonusSummary.Date) <= '%s'", DBField::create_field('Date', $params['EndDate'])->URLDate());
	        }
		}
		else{
        	$where[] = sprintf("DATE(BonusSummary.Date) <= '%s'", date('Y-m-t'));
        }
        
        if(isset($params['Username']) && $params['Username']){
        	$where[] = sprintf("Member.Username LIKE '%%%s%%'", $params['Username']);
        }
		
		$query = new SQLQuery();
		$query = $query->setFrom('BonusSummary')->setWhere($where)->setOrderBy($sort)->setLimit($limit)->setGroupBy('BonusSummary.MemberID')->addInnerJoin('Member', 'BonusSummary.MemberID = Member.ID')->selectField('SUM(BonusSummary.CPSA)', 'CPSA')->selectField('SUM(BonusSummary.CPBV)', 'CPBV')->selectField('SUM(BonusSummary.CSDSA)', 'CSDSA')->selectField('SUM(BonusSummary.CSDBV)', 'CSDBV')->selectField('SUM(BonusSummary.BS1)', 'BS1')->selectField('SUM(BonusSummary.BS2)', 'BS2')->selectField('SUM(BonusSummary.BS3)', 'BS3')->selectField('SUM(BonusSummary.BS4)', 'BS4')->selectField('SUM(BonusSummary.BS5)', 'BS5');

		$returnSet = new ArrayList();
		$this->total = array('CPSA' => 0, 'CPBV' => 0, 'CSDSA' => 0, 'CSDBV' => 0, 'CADJLPGBV' => 0, 'CADJRPGBV' => 0, 'BS1' => 0, 'BS2' => 0, 'BS3' => 0, 'BS4' => 0, 'BS5' => 0);
		foreach($query->execute() as $item){
			$this->total['CPSA'] += $item['CPSA'];
			$this->total['CPBV'] += $item['CPBV'];
			$this->total['CSDSA'] += $item['CSDSA'];
			$this->total['CSDBV'] += $item['CSDBV'];
			$this->total['CADJLPGBV'] += $item['CADJLPGBV'];
			$this->total['CADJRPGBV'] += $item['CADJRPGBV'];
			$this->total['BS1'] += $item['BS1'];
			$this->total['BS2'] += $item['BS2'];
			$this->total['BS3'] += $item['BS3'];
			$this->total['BS4'] += $item['BS4'];
			$data = new ArrayData($item);
			$returnSet->push($data);
		}

		return $returnSet;
	}

	public function columns() {
		$fields = array(
			'Username' => array(
				'title' => _t('BonusSummaryReport.USERNAME', 'Username')
			),
			'Name' => array(
				'title' => _t('BonusSummaryReport.NAME', 'Name'),
				'formatting' => function($value, $item) {
				    return Distributor::get_name_by_id($item->MemberID);
                }
			),
			'CSDSA' => array(
                'title' => _t('BonusSummaryReport.SALE_AMOUNT', 'Sale Amount'),
                'casting' => 'Double->Nice'
            ),
			'CSDBV' => array(
                'title' => _t('BonusSummaryReport.SALE_BV', 'Sale BV'),
                'casting' => 'Int->Nice'
            ),
            'BS1' => array(
                'title' => _t('BonusSummaryReport.UNILEVEL_BONUS', 'Unilevel Bonus'),
                'casting' => 'Double->Nice'
            ),
            'BS2' => array(
                'title' => _t('BonusSummaryReport.INVEST_PROGRAM_BONUS', 'Invest Program Bonus'),
                'casting' => 'Double->Nice'
            ),
            'BS3' => array(
                'title' => _t('BonusSummaryReport.MATCHING_BONUS', 'Macthing Bonus'),
                'casting' => 'Double->Nice'
            ),
            'BS4' => array(
                'title' => _t('BonusSummaryReport.PAIRING_BONUS', 'Pairing Bonus'),
                'casting' => 'Double->Nice'
            )
		);
		
		return $fields;
	}
	
	public function parameterFields() {
		return FieldList::create(
            FieldGroup::create(
            	DateField::create('filters[StartDate]', '', date('Y-m-01'))->addExtraClass('no-change-track'),
				DateField::create('filters[EndDate]', '', date('Y-m-t'))->addExtraClass('no-change-track')
			)->setTitle(_t('BonusSummaryReport.DATE', 'Date')),
			UsernameField::create('Username', _t('BonusSummaryReport.USERNAME', 'Username')),
			HiddenField::create('Submit', 'Submit', 1)
		);
	}

	public function providePermissions() {
        return array(
            'VIEW_BonusSummaryReport' => array(
                'name' => _t('BonusSummaryReport.PERMISSION_VIEW', 'Allow view access right ({title})', '', array('title' => $this->title())),
                'category' => _t('BonusSummaryReport.PERMISSIONS_CATEGORY', 'Report')
            )
        );
    }
}
